package cc.ufinity.networkdiagnose.widget;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.net.wifi.WifiInfo;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.SimpleFTP;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.view.R;

public class FtpDownloadWidget extends GeneralTestWidget {

    private Activity ctx;
    //private LinearLayout ftpTestChartLayout;
    private Button backBtn;
    private ScrollView scrView;
    private LinearLayout ftpTestDetail;
//    private String localFilePath = Environment.getExternalStorageDirectory() + "/ftptest/";
    private String localFilePath = "";
    private String remotePathUp = "/ftptest/"+GlobalApp.ftp_GUID+"/";
    private String remotePathDown = "/ftp/";
	//private String fileName = "ftp_test.png";
    private String fileNameDown = "2M.rar";
	private String fileNameUp = "1.doc";
    private ImageView pointImageView;
	//private TextView timesView;
	//private TextView timeRateView;
    private static final int COUNT = 10;
    private int testedTimes;
    private int testedTimesUp = 0;
    private int testedTimesDown = 0;
    private float lastSpeed=0;
    private Handler ftpTestHandler;
    private boolean logouting= false;
    private TextView uploadTextId;
    //private TextView downTextId;
    private WlanManager wlanManager;
    private float lastLast;
    private static SimpleFTP simpleFTP;
    private LinearLayout llChart; 
    private ProgressBar pb;
    private TextView tv_complet, tv_rate;
    private Button bt_stop;
    private int completSize;
    private boolean stop = false;
    private float rate;
    
    public FtpDownloadWidget(Activity context) {
        super(context);
        this.ctx = context;
        if(GlobalApp.DEBUG) {
        	localFilePath = Environment.getExternalStorageDirectory() + "/ftptest/";
        } else {
        	localFilePath =  ctx.getFilesDir().getParent()+ File.separator + "ftptest" + File.separator;
        }
        try {
	    	File fileDir = new File(localFilePath);
	        fileDir.mkdir();
		} catch (Exception e) {
			e.printStackTrace();
		}	
        inflate(ctx, R.layout.ftp_download_widget, this);
        //ftpTestChartLayout = (LinearLayout) this.findViewById(R.id.ftpTestChartLayout);
        backBtn = (Button) this.findViewById(R.id.ftp_test_btnback);
        bt_stop = (Button) this.findViewById(R.id.btn_ftp_stop);
        scrView = (ScrollView) this.findViewById(R.id.ftp_test_ScrView);
        ftpTestDetail = (LinearLayout) this.findViewById(R.id.ftp_test_detail);
        pointImageView = (ImageView)findViewById(R.id.pointImageView);
        pb = (ProgressBar)findViewById(R.id.ftp_large_progress);
        pb.setMax(GlobalApp.fileSizeLargerDown);
        tv_complet = (TextView)findViewById(R.id.ftp_large_complet);
        tv_complet.setText("0%");
        tv_rate = (TextView)findViewById(R.id.ftp_large_rate);
        tv_rate.setText("0Kb/s");
      //  uploadTextId = (TextView)findViewById(R.id.uploadTextId);
        //downTextId = (TextView)findViewById(R.id.downTextId);
        //timeRateView = (TextView)findViewById(R.id.timeRateView);
        //timesView = (TextView)findViewById(R.id.timesView);
       // sucRateView = (TextView)findViewById(R.id.sucRateView);
        //timeRateView.setText("0 Kb/s");
        //timesView.setText(testedTimes+"/"+COUNT +"次");
        llChart = (LinearLayout)findViewById(R.id.chart);
        bindView();
      //  btnRetest = (Button) findViewById(R.id.btn_ftp_retest);
        bt_stop.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				stop = true;
				try {
					simpleFTP.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // back(ctx);
            	try {
					simpleFTP.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
             	switch(GlobalApp.nowNetType) {
 				case 1:
 					backToTestWidget_Wlan(ctx);
 					break;
 				case 2:
 					backToTestWidget_TD(ctx);
 					break;
 				case 3:
 					backToTestWidget_GSM(ctx);
 					break;
 				default:
 					break;
 				}
             }
        });

        ftpTestHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.FTP_DOWNLOAD_DONE:
                	dismissMessageDialog();
                	//System.out.println(wlanManager.checkNetworkType()+"  ftp 2===========wlanManager.checkNetworkType()");
                    updateDownloadProgress();
                    break;
                case MessageWhat.DONE:
                	updateDownloadProgress();
                    //updateTestResult();
                    break;
                case MessageWhat.FTP_CONNECT_TIMEOUT:
                	dismissMessageDialog();
//                    drawLineChart();
                    showMessage(ctx, "FTP连接超时.");
                    break;
                case MessageWhat.NETWORK_INVALID:
                	dismissMessageDialog();
                    showMessage(ctx, "无法连接至因特网.");
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    showMessage(ctx, "无法获取FTP账号");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                	dismissMessageDialog();
                    showMessage(ctx, "FTP登录失败");
                    break;
                    
                case SimpleFTP.CONNECTSUCCEED:
                	System.out.println("--------simpleFTP连接成功");
                	/*if(msg.arg1 > 0) {
                        showProgressDialog(ctx, "正在进行FTP测试...", msg.arg1);
                	} else {
                		showMessage(ctx, "simpleFTP连接成功");
                	}*/
                	break;
                case SimpleFTP.DOWNLOAD:
                	dismissMessageDialog();
                	//setDialogProgress(simpleFTP.getCompletedSize());
                	updateDownloadProgress();
                	//System.out.println("--------simpleFTP实时下载速度：" + simpleFTP.getNowDownSpeed());
                	break;
//                case SimpleFTP.UPOVER:
//                	setDialogProgress(0);
//                	break;
                case SimpleFTP.DOWNOVER:
                	updateDownloadProgress();
                	tv_complet.setText("100%");
                    //updateTestResult();
                	break;
//                case SimpleFTP.TIMEOUTUP:
//                	dismissMessageDialog();
//                    //上传超时
//                	StringBuffer sb = new StringBuffer();
//                    sb.append("上传超时");
//                    TextView tv = new TextView(ctx);
//                    tv.setTextSize(12);
//                    tv.setText(sb);
//                    ftpTestDetail.addView(tv);
//                	break;
                case SimpleFTP.TIMEOUTDOWN:
                	//下载超时
                	dismissMessageDialog();
                	updateDownloadProgress();
                	StringBuffer sb2 = new StringBuffer();
                	if(stop) {
                		sb2.append("FTP下载已停止");
                	} else {
                		sb2.append("FTP下载超时");
                	}
                    TextView tv2 = new TextView(ctx);
                    tv2.setTextSize(12);
                    tv2.setText(sb2);
                    tv2.setTextColor(Color.BLACK);
                    ftpTestDetail.addView(tv2);
                    //updateTestResult();
                	break;
                }
            }
        };
        wlanManager = new WlanManager(ctx);
    }
    private void bindView(){
    	switch(GlobalApp.nowNetType) {
			case 1:
				llChart.setBackgroundResource(R.drawable.dialchart_ftpdown);
				break;
			case 2:
			case 3:
				llChart.setBackgroundResource(R.drawable.dialchart_ftpdown_tdgsm);
				break; 
			default:
				break;
			}
    }

    private void initTestData() {
    	fileNameDown = GlobalApp.fileNameLargerDown;
    	getSimpleFTP().setFileSizeDown(GlobalApp.fileSizeLargerDown);
    	
        /*if(wlanManager.checkNetworkType() == 1) { 
        	fileNameDown = GlobalApp.fileNameWlanDown;
        	simpleFTP.setFileSizeDown(GlobalApp.fileSizeWlanDown);
        } else {
        	if(tm.getNetworkType().equals(WlanManager.TD)) { 
            	fileNameDown = GlobalApp.fileNameTDDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeTDDown);
        	} else { 
            	fileNameDown = GlobalApp.fileNameGSMDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeGSMDown);
        	}
        }*/
         
    }

    private void updateDownloadProgress() {
    	testedTimes++;
    	testedTimesDown++;
        DecimalFormat df = new DecimalFormat("#0.00");
        //float dwSpeed = (float) getSimpleFTP().getCurrentSpeed();
        completSize = getSimpleFTP().getCompletedSize();
        float dwSpeed = (float)completSize*1000/1024*8/(System.currentTimeMillis()-getSimpleFTP().getDwTime()[0]);
        //dwSpeed *= 8;//将KB转化为Kb
        StringBuffer sb = new StringBuffer();
        sb.append("平均下载速度为：").append(df.format(dwSpeed)).append("Kb/s");
        TextView tv = new TextView(ctx);
        tv.setTextSize(12);
        tv.setText(sb);
        tv.setTextColor(Color.BLACK);
        ftpTestDetail.addView(tv);
        rotateDialChart(lastSpeed,dwSpeed);
        lastSpeed = dwSpeed;
        setScrollViewDown(scrView);
        
        updateProgressBar(df.format(dwSpeed));
    }
    private void updateProgressBar(String  rate) {
    	//completSize = getSimpleFTP().getCompletedSize();
    	pb.setProgress(completSize);
    	tv_complet.setText((long)completSize*100/GlobalApp.fileSizeLargerDown + "%");
//    	DecimalFormat df = new DecimalFormat("#0.00");
    	//float rate = (float)completSize*1000/1024*8/(System.currentTimeMillis()-getSimpleFTP().getDwTime()[0]);
    	tv_rate.setText(rate + "Kb/s");
    }
    /*private void updateTestResult() {
        DecimalFormat df = new DecimalFormat("#0.00");
        float rate = (float)completSize*1000/1024*8/(System.currentTimeMillis()-getSimpleFTP().getDwTime()[0]);
        StringBuffer s = new StringBuffer();
        s.append(" 平均下载速度：").append(df.format(rate)).append(" Kb/s");
        TextView tv = new TextView(ctx);
        tv.setTextColor(Color.CYAN);
        tv.setTextSize(13);
        tv.setText(s);
        ftpTestDetail.addView(tv);
        setScrollViewDown(scrView);
    }*/

    public void statFtpTest() {
    	
        final FTPConfig ftp = this.getFTPConfig(ctx);
 System.out.println("FTP信息：" + ftp.address + "--" + ftp.port + "--" + ftp.userName + "--" + ftp.password); ////////// 
        if (ftp!=null && ftp.userName!=null && ftp.userName.length() > 0) {
            int type = NetworkManager.detectNetworkConnectivity(ctx);
            if (type == -1) {
                sendMsg(MessageWhat.NETWORK_INVALID, ftpTestHandler);
            } else {
            	showMessageDialog(ctx, "正在连接FTP服务器...");
                new Thread() {
                    public void run() {
                    	 if (!logouting) {
       					  logouting = true;
       					  WifiInfo wifiInfo = wlanManager.getCurrentNetwork();
       					  if(wifiInfo!= null && wifiInfo.getSSID() != null && wifiInfo.getSSID().equals(WlanManager.SSID_CMCC)){
       							WebAuthManager wManager = new WebAuthManager(ctx);
       							String  defaultUrl = ctx.getResources().getString(R.string.default_url);
       					        DBManager db = new DBManager(ctx);
       							Account config = db.getAccount();
       							String userName ="",pwd="";
       							if(null != config){ 
//       								String USER[]=AccountConfigWidget.stringAnalytical(config.userName);
//    								String PWD[]=AccountConfigWidget.stringAnalytical(config.password);
//    								userName = USER[0];
//       								pwd = PWD[0];
       								userName = config.userName;
       								pwd = config.password; 
       								wManager.auth(defaultUrl, userName, pwd);
       							}
       						}
       				    }
                    	setSimpleFTP(new SimpleFTP(ftp.address, ftp.port, 
             					ftp.userName, ftp.password, ftpTestHandler));
                        initTestData();
            	        try {  
            	        	getSimpleFTP().connect();
            	        	try {
            	                Thread.sleep(500);
            	            } catch (InterruptedException e) {}
            	            try {
            	            	getSimpleFTP().getLarge(localFilePath + fileNameDown, remotePathDown, fileNameDown);
            	            } catch (Exception e) {
            	            	Message msg = ftpTestHandler.obtainMessage();
                	        	msg.what = SimpleFTP.TIMEOUTDOWN;
                	        	msg.sendToTarget();
            	            }
            	        } catch (IOException e) {
            	        	Message msg = ftpTestHandler.obtainMessage();
            	        	msg.what = MessageWhat.FTP_LOGIN_FAILED;
            	        	msg.sendToTarget();
            	            e.printStackTrace();
            	        } finally {
            	            try {
            	            	getSimpleFTP().disconnect();
            	            } catch (IOException e) {
            	                e.printStackTrace();
            	            }
            	        }
                    }
                }.start();
            }
        } else {
        	Message msg = ftpTestHandler.obtainMessage();
        	msg.what = MessageWhat.FTP_ACCOUNT_INVALID;
        	msg.sendToTarget();
        }
    }

    public void rotateDialChart(float last,float now){
		
    	//float start = last/128*18;
		float start = lastLast;
	//	float end = now/128*18;
		float end = 0;
		if(GlobalApp.nowNetType ==1 ){
			//依据图片计算角度
			if(now >= 0 && now < 1024){
				end = now/256*18;
			}
			else if (now >= 1024 && now < 4*1024) {
				end = 1024/256*18 + (now-1024)/1024 *18; 
			}
			else if(now >= 4*1024 && now < 10*1024){
				end = 1024/256*18 + 3*1024/1024*18 + (now-4*1024)/2048 * 18;
			}else if ( now >= 10* 1024) {
				end = 180f;
			}
		}
		else if(GlobalApp.nowNetType ==2 || GlobalApp.nowNetType ==3) {
			//依据图片计算角度
			if(now >= 0 && now < 256){
				end = now/128*18;
			}
			else if (now >= 256 && now < 1024) {
				end = 256/128*18 + (now-256)/256 *18; 
			}
			else if(now >= 1*1024 && now < 3*1024){
				end = 256/128*18 + (1024-256)/256*18 +(now-1*1024)/512 * 18;
			}else if ( now >= 3* 1024 && now <= 4*1024) {
				end = 9 + (now - 3*1024)/1024*18;
			}else if (now >= 4*1024) {
				end = 180f;
			}
		}
		
		lastLast = end;
	// 旋转动画效果 
		 AnimationSet animation=new AnimationSet(true);
		 RotateAnimation rotateAnimation=new RotateAnimation(start, end,
				Animation.RELATIVE_TO_SELF, 1f,
				Animation.RELATIVE_TO_SELF, 0.25f);
	//	AlphaAnimation alpha=new AlphaAnimation(1, 0);
		 /*ScaleAnimation acale=new ScaleAnimation(1, 0.1f, 1,0.1f,
				 Animation.RELATIVE_TO_SELF, 0.5f,
				 Animation.RELATIVE_TO_SELF, 0.5f);
			acale.setDuration(50);
			animation.addAnimation(acale);*/
		 rotateAnimation.setDuration(50);
		 animation.addAnimation(rotateAnimation);
		 animation.setFillEnabled(true);
		 animation.setFillAfter(true);
	//	 alpha.setDuration(3000);
	//	 animation.addAnimation(alpha);
		 pointImageView.startAnimation(animation); 
	}
	public static void setSimpleFTP(SimpleFTP simpleFTP) {
		FtpDownloadWidget.simpleFTP = simpleFTP;
	}
	public static SimpleFTP getSimpleFTP() {
		return simpleFTP;
	}
}
